package com.zhu.controller;

import com.zhu.pojo.Customer;
import com.zhu.pojo.Result;
import com.zhu.service.CustomerService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;
import java.util.StringTokenizer;

@RestController
@RequestMapping("/customer")
@Slf4j
public class CustomerController {
    @Autowired
    private CustomerService customerService;

    @PostMapping("/insert")
    public Result insert(@RequestBody Customer customer){
        try{
            customerService.insert(customer);
            return Result.ok();
        }catch (Exception e){
            e.printStackTrace();
            return Result.fail("插入时发生异常");
        }
    }

    @PostMapping("/select")
    public Result select(@RequestBody String customer_name){
        Customer s = customerService.select(customer_name);
        if(s==null) return Result.fail("没找到"+customer_name+"这位用户");
        return Result.ok(s);
    }
    @PostMapping("/update")
    public Result update(@RequestBody Customer c){
        Integer id = customerService.selectIdByName(c.getName());
        if(id==null) return Result.fail("未找到该用户"+c.getName()+"这位用户");
        c.setId(id);
        try{
            customerService.update(c);
            return Result.ok(c);
        }catch (Exception e){
            e.printStackTrace();
            return Result.fail("修改时发生错误");
        }
    }

    @PostMapping("/getCustomerStatistics")
    @CrossOrigin
    public Result getCustomerStatistics(){
        return Result.ok(customerService.getCustomerStatistics());
    }

    @PostMapping("/searchAll")
    public Result searchAll(@RequestBody String name){
        try{
            List<Map<String,Object>> list =  customerService.searchAll(name);
            if(list==null) return Result.fail("查找失败");
            return Result.ok(list);
        }catch (Exception e){
            return Result.fail("查找时发生错误");
        }
    }

    @PostMapping("/delete")
    public Result delete(@RequestBody String name){
        try {
            customerService.delete(name);
            return Result.ok();
        }catch (Exception e){
            e.printStackTrace();
            return Result.fail("删除时发生错误");
        }
    }
}
